package game;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.Vector;

import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 * Highscore
 * 
 * @author Gustav Oberwandling
 * @since 29.05.2010
 */

/**
 * A class used for storing and showing game scores.
 */
public class RMSHighScore implements RecordComparator {
  /*
   * The RecordStore used for storing the game scores.
   */
  private RecordStore recordStore = null;

  /**
   * The constuctor opens the underlying record store, creating it if
   * necessary.
   */
  public RMSHighScore() {
    // Create a new record store for this example
    try {
    	recordStore = RecordStore.openRecordStore("byob", true);
    	//One-time initialization
    	if( recordStore.getNextRecordID() == 1 ){
    	    addScore(1230, "ALL");
    	    addScore(990, "BOB");
    	    addScore(800, "CHA");
    	    addScore(700, "DAV");
    	    addScore(600, "SIM");
    	    addScore(510, "FAB");
    	    addScore(450, "GUS");
    	    addScore(330, "HEN");
    	    addScore(210, "ISA");
    	    addScore(70, "JUL");
    	}
    }
    catch (RecordStoreException rse) {
    	System.out.println("Record Store Exception in the ctor." + rse);
    	rse.printStackTrace();
	}
  }
  
  /*
   * Part of the RecordComparator interface.
   */
  public int compare(byte[] rec1, byte[] rec2) {

    // Construct DataInputStreams for extracting the scores from
    // the records.
    ByteArrayInputStream bais1 = new ByteArrayInputStream(rec1);
    DataInputStream inputStream1 = new DataInputStream(bais1);
    ByteArrayInputStream bais2 = new ByteArrayInputStream(rec2);
    DataInputStream inputStream2 = new DataInputStream(bais2);
    int score1 = 0;
    int score2 = 0;
    try {
    	score1 = inputStream1.readInt();
    	score2 = inputStream2.readInt();
    }
    catch (EOFException eofe){
    	System.out.println(eofe);
    	eofe.printStackTrace();
    }
    catch (IOException eofe){
    	System.out.println(eofe);
    	eofe.printStackTrace();
    }

    // Sort by score
    if (score1 < score2) 
      return RecordComparator.FOLLOWS;
    else if (score1 > score2)
      return RecordComparator.PRECEDES;
    else
      return RecordComparator.EQUIVALENT;
  }

  /**
   * Add a new score to the storage.
   * 
   * @param score
   *            the score to store.
   * @param playerName
   *            the name of the play achieving this score.
   */
  public void addScore(int score, String playerName) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream outputStream = new DataOutputStream(baos);
    try {
      outputStream.writeInt(score);
      outputStream.writeUTF(playerName);
    }
    catch (IOException ioe){
      System.out.println(ioe);
      ioe.printStackTrace();
    }

    byte[] b = baos.toByteArray();
    try {
      recordStore.addRecord(b, 0, b.length);
    }
    catch (RecordStoreException rse){
      System.out.println(rse);
      rse.printStackTrace();
    }
  }

  /**
   * This method prints all of the scores sorted by game score.
   */
  public Vector printScores() {
	Vector rv = new Vector();
    try {
      // Enumerate the records using the comparator implemented above to sort by game score.
      RecordEnumeration re = recordStore.enumerateRecords(null, this, true);

      try {
    	  int i=0;
          while (re.hasNextElement() || i<9){
            i++;
            int id = re.nextRecordId();
            ByteArrayInputStream bais = new ByteArrayInputStream(
                recordStore.getRecord(id));
            DataInputStream inputStream = new DataInputStream(bais);
            try {
              int score = inputStream.readInt();
              String playerName = inputStream.readUTF();
              rv.addElement(playerName+" "+score);
            }
            catch (EOFException eofe){
              System.out.println(eofe);
              eofe.printStackTrace();
            }
          }
        }
      catch (RecordStoreException rse){
          System.out.println(rse);
          rse.printStackTrace();
      }
      catch (IOException ioe){
          System.out.println(ioe);
          ioe.printStackTrace();
      }
    }
    catch (RecordStoreException rse){
      System.out.println(rse);
      rse.printStackTrace();
    }
    return rv;
  }

  
  /**
   * closeRecordStore()
   * 
   * This closes our open RecordStore when we are destroyed.
   * 
   * @param cond
   *            true if this is an unconditional destroy false if it is not
   *            (ignored here and treated as unconditional)
   */
  public void closeRecordStore(boolean cond) {
    try{
    	if(recordStore != null)
    		recordStore.closeRecordStore();
    }
    catch (Exception ignore){/*ignore this*/}
  }
}